package com.kay.config;

import com.kay.service.UserService;
import jdk.nashorn.internal.ir.annotations.Reference;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.core.io.buffer.DataBuffer;
import org.springframework.http.HttpStatus;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

/**
 * @Description:
 * 添加全局过滤，进⾏token的验证，⽤户微服务和验证码微服务的请求不过滤（⽹关调⽤下游⽤户微服务的token验证接⼝）
 * @Author: Kay
 * @CreateDate: 2021/9/28$ 15:17$
 * @UpdateUser: Kay
 * @UpdateDate: 2021/9/28$ 15:17$
 */
@Slf4j
@Component
public class UserInfoFilter implements GlobalFilter, Ordered {
    @Reference
    private UserService userService;

    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        log.info("this is UserInfoFilter .................................");
        ServerHttpRequest request = exchange.getRequest();
        ServerHttpResponse response = exchange.getResponse();

        String path = request.getURI().getPath(); //  /api/user/isRegistered/
        log.info("path --------------------------" + path);
        // ⽤户微服务和验证码微服务的请求不过滤 （⽹关调⽤下游⽤户微服务的token验证接⼝）
        if (path.startsWith("/api/user/info/")) {
            String[] split = path.split("/api/user/info/");
            if (split.length == 2 && StringUtils.isNotEmpty(split[1]) && !split[1].equals("undefined")) {
                String token = split[1];
                String email = userService.info(token);
                if (StringUtils.isNotEmpty(email)) {
                    return responseResult(response, HttpStatus.OK, email);
                }
            }

            // 决绝访问，返回
            return responseResult(response, HttpStatus.UNAUTHORIZED, "Request be denied!");
        }

        // 合法请求放行，执行后续的过滤器
        return chain.filter(exchange);
    }

    private Mono<Void> responseResult(ServerHttpResponse response, HttpStatus httpStatus, String data) {
        response.setStatusCode(httpStatus); // 状态码
        DataBuffer wrap = response.bufferFactory().wrap(data.getBytes());
        return response.writeWith(Mono.just(wrap));
    }

    /**
     * 返回值表示当前过滤器的顺序(优先级)，数值越小，优先级越高
     *
     * @return
     */
    @Override
    public int getOrder() {
        return 1;
    }
}
